<template>
  <div class="file_box">
    <el-card class="box-card">
      <div class="box">
        <input type="file" @change="inputChange" />
        <div class="icon">
          <span>
            <el-icon><lightning /></el-icon> 点击上传</span
          >
        </div>
      </div>
      <el-progress
        :text-inside="true"
        :stroke-width="15"
        :percentage="rate"
        status="success"
        :class="[dn ? 'dn' : '']"
      />
    </el-card>
  </div>
</template>
<script setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { uploadFile } from '../api/file'
const dn = ref(true)
const rate = ref(0)
let fileData = reactive(null)
function inputChange (e) {
  const [file] = e.target.files
  fileData = file
  uploadfile()
}
async function uploadfile () {
  if (!fileData) {
    ElMessage({
      type: 'error',
      message: '请选择文件'
    })
  }
  try {
    dn.value = false
    const form = new FormData()
    form.append('file', fileData)
    const { data } = await uploadFile(form, uploadProgress)
    if (data.code === 200) {
      fileData = null
      dn.value = true
      rate.value = 0
    }
    ElMessage({
      type: 'success',
      message: '上传成功'
    })
  } catch (error) {
    fileData = null
    dn.value = true
    rate.value = 0
  }
}
function uploadProgress (e) {
  rate.value = Number(((e.loaded / e.total) * 100).toFixed(0))
}
</script>
<style lang="less" scoped>
.file_box {
  height: 100%;
  .el-card {
    height: 100%;
    /deep/.el-card__body {
      height: 100%;
      .box {
        width: 50%;
        height: 200px;
        border: 1px solid dashed;
        border: 1px dashed;
        position: relative;
        input {
          width: 100%;
          height: 100%;
          opacity: 0;
          z-index: 100;
          position: absolute;
          z-index: 100;
        }
        .icon {
          position: absolute;
          top: 36%;
          left: 30%;
          span {
            font-size: 30px;
          }
        }
      }
      .el-progress {
        margin-top: 40px;
        width: 60%;
      }
      .el-tabs {
        height: 100%;
        .el-tabs__content {
          height: 100%;
          .el-tab-pane {
            height: 100%;
          }
        }
      }
    }
  }
}
.dn {
  display: none;
}
</style>
